<template>
	<div class="wrapper" style="min-height: 100vh; background-color: #f5f5f5; padding-bottom: 18vw;">

		<!-- 顶部应用栏 -->
		<header class="mdc-top-app-bar">
			<div class="mdc-top-app-bar__row">
				<section class="mdc-top-app-bar__section mdc-top-app-bar__section--align-start">
					<BackButton />
					<h1 class="mdc-top-app-bar__title">确认支付</h1>
				</section>
			</div>
		</header>

		<!-- 支付方式选择部分 -->
		<div class="payment-method-card">
			<div class="card-header">
				<i class="material-icons">payment</i>
				<h5>选择支付方式</h5>
			</div>
			<div class="payment-methods-list">
				<!-- 微信支付 -->
				<div 
					class="payment-item" 
					:class="{ active: paymentMethod === 'wechat' }"
					@click="paymentMethod = 'wechat'"
				>
					<div class="payment-item-left">
						<i class="material-icons payment-icon">account_balance_wallet</i>
						<span>微信支付</span>
					</div>
					<i class="material-icons check-icon" v-show="paymentMethod === 'wechat'">check_circle</i>
				</div>
				<!-- 支付宝支付 -->
				<div 
					class="payment-item" 
					:class="{ active: paymentMethod === 'alipay' }"
					@click="paymentMethod = 'alipay'"
				>
					<div class="payment-item-left">
						<i class="material-icons payment-icon">account_balance_wallet</i>
						<span>支付宝支付</span>
					</div>
					<i class="material-icons check-icon" v-show="paymentMethod === 'alipay'">check_circle</i>
				</div>
				<!-- 余额支付 -->
				<div 
					class="payment-item" 
					:class="{ active: paymentMethod === 'balance' }"
					@click="paymentMethod = 'balance'"
				>
					<div class="payment-item-left">
						<i class="material-icons payment-icon">account_balance</i>
						<span>余额支付</span>
					</div>
					<i class="material-icons check-icon" v-show="paymentMethod === 'balance'">check_circle</i>
				</div>
			</div>
			<!-- 余额支付时显示余额信息和密码输入 -->
			<div v-if="paymentMethod === 'balance'" class="balance-payment-section">
				<div class="balance-info">
					<p class="balance-label">账户余额：</p>
					<p class="balance-amount">¥<span>{{walletBalance.toFixed(2)}}</span></p>
				</div>
				<div class="password-input-wrapper">
					<label>支付密码：</label>
					<input 
						v-model="paymentPassword" 
						type="password" 
						placeholder="请输入6位支付密码"
						maxlength="6"
						class="password-input"
					>
				</div>
			</div>
		</div>

		<!-- 商家信息 -->
		<div class="business-card">
			<i class="material-icons business-icon">store</i>
			<h3>{{orders.businessName}}</h3>
		</div>

		<!-- 订单明细部分 -->
		<div class="order-items-card">
			<div class="card-header">
				<i class="material-icons">shopping_cart</i>
				<h5>订单明细</h5>
			</div>
			<div class="order-items-list">
				<div v-for="item in orders.priceDetails" :key="item.foodId" class="order-item">
					<div class="item-left">
						<img :src="getImg(item.foodImg)" @error="handleImageError" class="item-img">
						<div class="item-info">
							<p class="item-name">{{item.foodName}}</p>
							<p class="item-quantity">x {{item.quantity}}</p>
						</div>
					</div>
					<p class="item-price">¥{{roundToDecimalPlace(item.foodPrice*item.quantity,2)}}</p>
				</div>
				<div class="order-item delivery-fee-item">
					<div class="item-left">
						<i class="material-icons delivery-icon">local_shipping</i>
						<p class="item-name">配送费</p>
					</div>
					<p class="item-price">¥{{orders.deliveryPrice}}</p>
				</div>
			</div>
		</div>

		<!-- 合计部分 -->
		<div class="total-bar">
			<div class="total-info">
				<div class="price-row">
					<span class="price-label">商品合计：</span>
					<span class="price-amount">¥{{roundToDecimalPlace(subtotal,2)}}</span>
				</div>
				<div class="price-row" v-if="orders.couponDiscountAmount && orders.couponDiscountAmount > 0">
					<span class="price-label discount">
						<i class="material-icons discount-icon">card_giftcard</i>
						优惠券减免：
					</span>
					<span class="price-amount discount">-¥{{roundToDecimalPlace(orders.couponDiscountAmount,2)}}</span>
				</div>
				<div class="price-row" v-if="orders.levelDiscountAmount && orders.levelDiscountAmount > 0">
					<span class="price-label discount">
						<i class="material-icons discount-icon">military_tech</i>
						等级折扣：
					</span>
					<span class="price-amount discount">-¥{{roundToDecimalPlace(orders.levelDiscountAmount,2)}}</span>
				</div>
				<div class="price-row total">
					<span class="total-label">实付金额：</span>
					<span class="total-amount">¥{{roundToDecimalPlace(finalPrice,2)}}</span>
				</div>
				<div class="savings-tip" v-if="orders.couponDiscountAmount > 0 || orders.levelDiscountAmount > 0">
					<i class="material-icons">celebration</i>
					<span>已为您节省 ¥{{roundToDecimalPlace(totalSavings,2)}}</span>
				</div>
			</div>
			<button class="pay-button" @click="confirmPayment" :disabled="isLoading">
				<i class="material-icons">payment</i>
				<span>{{isLoading ? '支付中...' : '确认支付'}}</span>
			</button>
		</div>
	</div>
</template>

<script>
	import BackButton from '../components/BackButton.vue';
	export default{
		name:'PaymentPage',
		data(){
			return {
				orderId:this.$route.query.orderId,
				orders:{
					address: '',
					priceDetails: [],
					deliveryPrice: 0,
					totalPrice: 0,
					finalTotal: 0,
					couponDiscountAmount: 0,
					levelDiscountAmount: 0,
					businessName: ''
				},
				user:{},
				userLevel: 1,
				userDiscount: 99,
				paymentMethod: 'balance',
				walletBalance: 0,
				paymentPassword: '',
				isLoading: false
			}
		},
		created() {
			this.user = this.$getSessionStorage('user');
			console.log(this.user);
			// ...
			// 加载用户等级和折扣信息
			this.loadUserLevelInfo();
			
			// 加载钱包余额
			this.loadWalletBalance();
			
			// 获取订单信息
			this.fetchOrderInfo();
		},
		computed:{
			subtotal(){
				let subtotal = 0;
				if (this.orders.priceDetails && Array.isArray(this.orders.priceDetails)) {
					subtotal = this.orders.priceDetails.reduce((sum, item) => {
						return sum + ((item.foodPrice || 0) * (item.quantity || 0));
					}, 0);
				}
				subtotal += parseFloat(this.orders.deliveryPrice || 0);
				return subtotal;
			},
			levelDiscountAmount(){
				// 这里直接使用后端计算好的等级折扣金额，避免与后端逻辑不一致
				return parseFloat(this.orders.levelDiscountAmount || 0);
			},
			finalPrice(){
				// 实付金额直接使用后端返回的 finalTotal，确保与数据库一致
				// 如后端暂未提供，则回退到本地重新计算的价格
				const backendFinal = parseFloat(this.orders.finalTotal || 0);
				if (!isNaN(backendFinal) && backendFinal > 0) {
					return backendFinal;
				}
				// 回退逻辑：维持原有前端计算方式作为兜底
				let price = parseFloat(this.subtotal) || 0;
				if (this.orders.couponDiscountAmount && this.orders.couponDiscountAmount > 0) {
					price = Math.max(0, price - parseFloat(this.orders.couponDiscountAmount));
				}
				const discount = parseFloat(this.userDiscount) || 100;
				if (discount < 100) {
					price = Math.max(0, price - parseFloat(this.levelDiscountAmount));
				}
				return Math.max(0, price);
			},
			totalSavings(){
				// 优惠总额优先使用后端计算好的 discountAmount
				if (this.orders.discountAmount != null) {
					return Math.max(0, parseFloat(this.orders.discountAmount || 0));
				}
				let savings = 0;
				if (this.orders.couponDiscountAmount && this.orders.couponDiscountAmount > 0) {
					savings += parseFloat(this.orders.couponDiscountAmount) || 0;
				}
				savings += parseFloat(this.levelDiscountAmount) || 0;
				return Math.max(0, savings);
			},
			sexFilter(){
				if(!this.user || !this.user.userSex) return '';
				if(this.user.userSex==1)return '先生';
				else if(this.user.userSex==0)return '女士';
				else return '';
			}
		},
		methods:{
			getImg(path){
				if(!path) return this.getDefaultImage();
				// 如果是完整的HTTP URL，直接返回
				if(path.startsWith('http')) return path;
				// 如果是 base64 格式，直接返回
				if(path.startsWith('data:image')) return path;
				// 如果是相对路径（以/开头），拼接服务器地址
				if(path.startsWith('/')) {
					// 如果已经是 /img/ 开头，直接拼接
					if(path.startsWith('/img/')) {
						return 'http://localhost:8888' + path;
					}
					// 如果是其他路径（如 /2024-10-26/xxx.jpg），需要添加 /img 前缀
					return 'http://localhost:8888/img' + path;
				}
				// 其他情况，添加服务器前缀和路径分隔符
				return 'http://localhost:8888/img/' + path;
			},
			getDefaultImage(){
				// 返回一个包含食物emoji的SVG图片
				const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200"><rect width="200" height="200" fill="#f5f5f5" rx="10"/><text x="100" y="100" font-size="80" text-anchor="middle" dominant-baseline="central">🥤</text></svg>';
				return 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
			},
			handleImageError(event){
				event.target.src = this.getDefaultImage();
			},
			loadUserLevelInfo(){
				let user = this.$getSessionStorage('user');
				if (!user || !user.userId) {
					return;
				}
				
				this.$axios.post('UserController/user/info', this.$qs.stringify({
					userId: user.userId
				}), {
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded'
					}
				})
				.then(resp => {
					if (resp.data && (resp.data.code === 200 || resp.data.code === '200')) {
						const userInfo = resp.data.result || {};
						this.userLevel = userInfo.level || 1;
						this.userDiscount = userInfo.discount || 99;
					}
				})
				.catch(err => {
					console.error('加载用户等级信息失败:', err);
				});
			},
			fetchOrderInfo(){
				this.$axios
					.post('OrdersController/getOrdersById', this.$qs.stringify({
						orderId: this.orderId
					}))
					.then(response => {
						if (response.data && (response.data.code === 200 || response.data.code === '200') && response.data.result) {
							const orderData = response.data.result;
							this.orders = Object.assign({}, this.orders, orderData);
							console.log('订单信息加载成功:', this.orders);
						} else {
							throw new Error('订单数据为空或响应码错误');
						}
					})
					.catch(error => {
						console.error('获取订单信息失败:', error);
						alert('获取订单信息失败，请返回重试');
						this.$router.push({ path: '/orderList' });
					});
			},
			roundToDecimalPlace(num, decimalPlaces) {
				const factor = Math.pow(10, decimalPlaces);
				return Math.round(num * factor) / factor;
			},
			loadWalletBalance(){
				if (!this.user || !this.user.userId) {
					return;
				}
				
				this.$axios
					.post('wallet/info', this.$qs.stringify({
						walletId: this.user.userId
					}))
					.then(response => {
						if (response.data && (response.data.code === 200 || response.data.code === '200')) {
							const walletInfo = response.data.result || {};
							this.walletBalance = parseFloat(walletInfo.availableBalance || walletInfo.balance || 0);
						}
					})
					.catch(error => {
						console.error('获取钱包余额失败:', error);
						this.walletBalance = 0;
					});
			},
			confirmPayment(){
				if (this.isLoading) {
					return;
				}

				if (this.paymentMethod === 'balance') {
					this.handleWalletPayment();
				} else if (this.paymentMethod === 'wechat') {
					this.handleThirdPartyPayment('wechat');
				} else if (this.paymentMethod === 'alipay') {
					this.handleThirdPartyPayment('alipay');
				}
			},
			handleWalletPayment(){
				// 验证支付密码
				if (!this.paymentPassword || this.paymentPassword.length < 6) {
					alert('请输入6位支付密码');
					return;
				}

				// 验证余额
				if (parseFloat(this.walletBalance) < parseFloat(this.finalPrice)) {
					alert('账户余额不足，请先充值');
					return;
				}

				this.isLoading = true;
				this.$axios
					.post('OrdersController/payment', this.$qs.stringify({
						orderId: this.orderId,
						state: 1,
						paymentType: 'wallet',
						payPwd: this.paymentPassword,
						amount: this.roundToDecimalPlace(this.orders.finalTotal || this.finalPrice, 2)
					}))
					.then(response => {
						this.isLoading = false;
						if (response.data && (response.data.code === 200 || response.data.code === '200')) {
							alert('支付成功！');
							// 触发钱包更新事件
							if (window.dispatchEvent) {
								window.dispatchEvent(new CustomEvent('wallet-balance-updated'));
							}
							this.$router.push({ path: '/orderList' });
						} else {
							alert('支付失败：' + (response.data.message || '请重试'));
						}
					})
					.catch(error => {
						this.isLoading = false;
						console.error('支付错误:', error);
						alert('支付过程中出现错误，请稍后重试');
					});
			},
			handleThirdPartyPayment(type){
				const paymentName = type === 'wechat' ? '微信' : '支付宝';
				console.log(`使用${paymentName}支付，订单号：${this.orderId}`);

				this.isLoading = true;
				this.$axios
					.post('OrdersController/payment', this.$qs.stringify({
						orderId: this.orderId,
						state: 1,
						paymentType: type,
						amount: this.roundToDecimalPlace(this.orders.finalTotal || this.finalPrice, 2)
					}))
					.then(response => {
						this.isLoading = false;
						if (response.data && (response.data.code === 200 || response.data.code === '200')) {
							alert(`${paymentName}支付成功！`);
							// 触发钱包更新事件
							if (window.dispatchEvent) {
								window.dispatchEvent(new CustomEvent('wallet-balance-updated'));
							}
							this.$router.push({ path: '/orderList' });
						} else {
							alert(`${paymentName}支付失败，请重试`);
						}
					})
					.catch(error => {
						this.isLoading = false;
						console.error(`${paymentName}支付错误:`, error);
						alert(`${paymentName}支付过程中出现错误，请稍后重试`);
					});
			}
		},
		components: {
			BackButton
		}
	}
</script>

<style scoped>
	.wrapper {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 18vw;
	}

	/****************** header部分 ******************/
	/* 顶部应用栏 */
	.mdc-top-app-bar {
		background-color: #1976D2;
		color: white;
		position: sticky;
		top: 0;
		z-index: 100;
		box-shadow: 0 2px 4px rgba(0,0,0,0.1);
	}

	.mdc-top-app-bar__row {
		display: flex;
		align-items: center;
		height: 72px;
		padding: 0 20px;
	}

	.mdc-top-app-bar__section {
		display: flex;
		align-items: center;
		gap: 16px;
		flex-direction: row;
	}

	.mdc-top-app-bar__title {
		font-size: 22px;
		font-weight: 500;
		margin: 0;
		white-space: nowrap;
		line-height: 1;
	}

	/****************** 支付方式卡片 ******************/
	.payment-method-card {
		width: 100%;
		margin-top: 0;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: #fff;
		border-radius: 0 0 20px 20px;
		padding: 4vw;
		box-sizing: border-box;
		box-shadow: 0 4px 12px rgba(0,0,0,0.15);
	}

	.payment-methods-list {
		display: flex;
		flex-direction: column;
		gap: 2vw;
		margin-top: 3vw;
	}

	.payment-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 3vw;
		background: rgba(255,255,255,0.15);
		border-radius: 12px;
		cursor: pointer;
		transition: all 0.3s;
		border: 2px solid transparent;
	}

	.payment-item:active {
		transform: scale(0.98);
	}

	.payment-item.active {
		background: rgba(255,255,255,0.25);
		border-color: rgba(255,255,255,0.5);
	}

	.payment-item-left {
		display: flex;
		align-items: center;
		gap: 2vw;
	}

	.payment-icon {
		font-size: 5vw;
		opacity: 0.9;
	}

	.payment-item-left span {
		font-size: 4vw;
		font-weight: 500;
	}

	.check-icon {
		font-size: 5vw;
		opacity: 0.8;
	}

	.balance-info {
		margin-top: 3vw;
		padding: 3vw;
		background: rgba(255,255,255,0.15);
		border-radius: 12px;
		text-align: center;
	}

	.balance-label {
		font-size: 3.5vw;
		margin: 0 0 1vw 0;
		opacity: 0.9;
	}

	.balance-amount {
		font-size: 5vw;
		font-weight: 700;
		margin: 0;
		color: #FFD700;
	}

	.balance-amount span {
		font-size: 6vw;
	}

	.balance-payment-section {
		margin-top: 2vw;
	}

	.password-input-wrapper {
		display: flex;
		align-items: center;
		gap: 2vw;
		margin-top: 2vw;
		padding: 2.5vw;
		background: rgba(255,255,255,0.15);
		border-radius: 12px;
	}

	.password-input-wrapper label {
		font-size: 3.8vw;
		color: rgba(255,255,255,0.9);
		white-space: nowrap;
		font-weight: 500;
	}

	.password-input {
		flex: 1;
		padding: 2.5vw;
		border: 2px solid rgba(255,255,255,0.3);
		border-radius: 8px;
		font-size: 4vw;
		outline: none;
		transition: all 0.3s ease;
		background-color: rgba(255,255,255,0.9);
		color: #333;
	}

	.password-input:focus {
		border-color: rgba(255,255,255,0.8);
		box-shadow: 0 0 0 3px rgba(255,255,255,0.2);
	}

	.password-input::placeholder {
		color: #999;
	}

	.card-header {
		display: flex;
		align-items: center;
		gap: 2vw;
		margin-bottom: 3vw;
	}

	.card-header .material-icons {
		font-size: 5vw;
	}

	.card-header h5 {
		font-size: 3.5vw;
		font-weight: 400;
		margin: 0;
		opacity: 0.9;
	}

	.order-info-address {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: rgba(255,255,255,0.15);
		padding: 3vw;
		border-radius: 12px;
		margin-bottom: 3vw;
		cursor: pointer;
		transition: all 0.3s;
	}

	.order-info-address:active {
		background-color: rgba(255,255,255,0.25);
	}

	.address-text {
		flex: 1;
		font-size: 4.5vw;
		font-weight: 600;
		margin: 0;
	}

	.order-info-address .material-icons {
		font-size: 6vw;
		opacity: 0.8;
	}

	.user-info {
		display: flex;
		align-items: center;
		gap: 2vw;
		font-size: 3.2vw;
		opacity: 0.9;
	}

	.user-info .material-icons {
		font-size: 4vw;
	}

	/****************** 商家信息卡片 ******************/
	.business-card {
		display: flex;
		align-items: center;
		gap: 3vw;
		padding: 4vw;
		background-color: #fff;
		margin: 3vw 0;
		border-radius: 16px;
		box-shadow: 0 2px 8px rgba(0,0,0,0.08);
	}

	.business-icon {
		font-size: 6vw;
		color: #667eea;
	}

	.business-card h3 {
		font-size: 4.5vw;
		font-weight: 600;
		color: #333;
		margin: 0;
	}

	/****************** 订单明细卡片 ******************/
	.order-items-card {
		background-color: #fff;
		border-radius: 16px;
		margin: 3vw;
		box-shadow: 0 2px 12px rgba(0,0,0,0.08);
		overflow: hidden;
	}

	.order-items-card .card-header {
		background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
		padding: 3vw 4vw;
		margin: 0;
	}

	.order-items-card .card-header .material-icons {
		color: #667eea;
	}

	.order-items-card .card-header h5 {
		color: #333;
		font-weight: 600;
		font-size: 4vw;
	}

	.order-items-list {
		padding: 2vw 0;
	}

	.order-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 3vw 4vw;
		border-bottom: 1px solid #f0f0f0;
	}

	.order-item:last-child {
		border-bottom: none;
	}

	.item-left {
		display: flex;
		align-items: center;
		gap: 3vw;
		flex: 1;
	}

	.item-img {
		width: 14vw;
		height: 14vw;
		border-radius: 10px;
		object-fit: cover;
		box-shadow: 0 2px 6px rgba(0,0,0,0.1);
	}

	.item-info {
		flex: 1;
	}

	.item-name {
		font-size: 3.8vw;
		font-weight: 500;
		color: #333;
		margin: 0 0 1vw 0;
	}

	.item-quantity {
		font-size: 3.2vw;
		color: #999;
		margin: 0;
	}

	.item-price {
		font-size: 4.2vw;
		font-weight: 600;
		color: #667eea;
		margin: 0;
	}

	.delivery-fee-item {
		background-color: #f8f9fa;
	}

	.delivery-icon {
		font-size: 5vw;
		color: #667eea;
	}

	.delivery-fee-item .item-name {
		margin: 0;
	}

	/****************** 合计部分 ******************/
	.total-bar {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		min-height: 16vw;
		background-color: #fff;
		box-shadow: 0 -2px 12px rgba(0,0,0,0.1);
		display: flex;
		align-items: flex-start;
		padding: 2vw 4vw;
		box-sizing: border-box;
		gap: 2vw;
		z-index: 100;
	}

	.total-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 0.8vw;
		padding-top: 1vw;
	}

	.price-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 3.2vw;
	}

	.price-row.total {
		border-top: 1px solid #e0e0e0;
		padding-top: 0.8vw;
		margin-top: 0.8vw;
	}

	.price-label {
		color: #666;
	}

	.price-label.discount {
		color: #4CAF50;
	}

	.price-amount {
		font-weight: 600;
		color: #333;
	}

	.price-amount.discount {
		color: #4CAF50;
	}

	.total-label {
		font-size: 3.8vw;
		color: #666;
		font-weight: 600;
	}

	.total-amount {
		font-size: 5.5vw;
		font-weight: 700;
		color: #ff6b6b;
	}

	.discount-icon {
		font-size: 3.5vw;
		vertical-align: middle;
		margin-right: 1vw;
	}

	.savings-tip {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 1vw;
		margin-top: 0.5vw;
		padding: 1.2vw 1.5vw;
		background: linear-gradient(135deg, rgba(76, 175, 80, 0.1) 0%, rgba(76, 175, 80, 0.05) 100%);
		border-radius: 6px;
		border: 1px solid rgba(76, 175, 80, 0.2);
	}

	.savings-tip .material-icons {
		font-size: 2.8vw;
		color: #4CAF50;
		flex-shrink: 0;
	}

	.savings-tip span {
		font-size: 2.8vw;
		color: #4CAF50;
		font-weight: 600;
		white-space: nowrap;
	}

	.pay-button {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: #fff;
		border: none;
		border-radius: 8px;
		padding: 2.5vw 4vw;
		font-size: 3.5vw;
		font-weight: 600;
		cursor: pointer;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 1.5vw;
		box-shadow: 0 4px 12px rgba(102,126,234,0.4);
		transition: all 0.3s;
		flex-shrink: 0;
		white-space: nowrap;
	}

	.pay-button:active {
		transform: scale(0.95);
		box-shadow: 0 2px 8px rgba(102,126,234,0.3);
	}

	.pay-button:disabled {
		background: #ccc;
		cursor: not-allowed;
		box-shadow: none;
		opacity: 0.7;
	}

	.pay-button:disabled:active {
		transform: none;
	}

	.pay-button .material-icons {
		font-size: 4vw;
	}
</style>